"""
交易服务核心业务逻辑
====================

基于现有的MainTradingEngine和OmsEngine设计的交易服务业务逻辑
提供订单管理、交易执行、持仓计算、资金管理等核心功能
"""

import asyncio
import logging
from typing import Dict, List, Optional, Any, Tuple
from decimal import Decimal
from datetime import datetime, timedelta
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, or_, desc, func, update, delete
from sqlalchemy.orm import selectinload
import uuid
import json

from shared.data.models.trading import (
    Order, Trade, Position, Account,
    Contract, Gateway, Strategy, Risk,
    Audit, OrderStatus, OrderDirection, TradeDirection,
    PositionDirection, GatewayStatus
)
from ..schemas.trading_schemas import (
    OrderRequest, OrderUpdate, OrderQueryParams, TradeQueryParams,
    PositionQueryParams, ContractQueryParams, GatewayRequest,
    StrategyRequest, StrategyControlRequest, TradingStatistics
)
from ..core.exceptions import (
    TradingServiceError, OrderNotFoundError, InsufficientFundsError,
    GatewayNotConnectedError, StrategyNotFoundError, RiskCheckFailedError
)
from ..core.events import EventManager, TradingEventType
from ..core.risk_manager import RiskManager
from ..core.position_calculator import PositionCalculator


class TradingService:
    """
    交易服务核心类
    
    基于现有的MainTradingEngine和OmsEngine架构设计
    提供完整的交易生命周期管理功能
    """
    
    def __init__(self, redis_client, event_manager: Optional[EventManager] = None):
        """
        初始化交易服务
        
        Args:
            redis_client: Redis客户端
            event_manager: 事件管理器
        """
        self.redis_client = redis_client
        self.event_manager = event_manager or EventManager()
        
        # 核心组件
        self.risk_manager = RiskManager(redis_client)
        self.position_calculator = PositionCalculator()
        
        # 状态管理 (主要用于非持久化状态)
        self._gateway_connections: Dict[str, Any] = {}
        self._strategy_instances: Dict[str, Any] = {}
        
        # 缓存管理
        self._contract_cache: Dict[str, Contract] = {}
        self._position_cache: Dict[str, Position] = {}
        
        # 日志记录
        self.logger = logging.getLogger(__name__)
        
        # 性能统计
        self._order_count = 0
        self._trade_count = 0
        self._error_count = 0
        
        self.logger.info("交易服务已初始化 (Stateless Mode)")
    
    # ==================== 订单管理 ====================
    
    async def create_order(self, session: AsyncSession, user_id: str, order_request: OrderRequest) -> Dict[str, str]:
        """
        创建交易订单
        
        Args:
            session: 数据库会话
            user_id: 用户ID
            order_request: 订单请求
            
        Returns:
            创建结果包含订单ID和订单编号
            
        Raises:
            RiskCheckFailedError: 风控检查失败
            InsufficientFundsError: 资金不足
            GatewayNotConnectedError: 网关未连接
        """
        try:
            # 1. 风控检查
            await self._perform_risk_check(session, user_id, order_request)
            
            # 2. 验证合约信息
            contract = await self._get_contract(session, order_request.symbol, order_request.exchange)
            if not contract:
                raise TradingServiceError(f"合约不存在: {order_request.symbol}.{order_request.exchange}")
            
            # 3. 检查资金充足性
            await self._check_funds_sufficiency(session, user_id, order_request)
            
            # 4. 生成订单ID
            order_id = f"ORD_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8].upper()}"
            
            # 5. 创建订单记录
            order = Order(
                id=str(uuid.uuid4()),
                order_id=order_id,
                user_id=user_id,
                strategy_id=order_request.strategy_id,
                symbol=order_request.symbol,
                exchange=order_request.exchange,
                direction=order_request.direction,
                offset=order_request.offset,
                order_type=order_request.order_type,
                volume=order_request.volume,
                price=order_request.price or Decimal('0'),
                remaining_volume=order_request.volume,
                status=OrderStatus.SUBMITTING,
                reference=order_request.reference,
                notes=order_request.notes,
                created_at=datetime.utcnow()
            )
            
            session.add(order)
            await session.flush()  # 使用flush来获取ID，但不提交事务
            
            # 6. 发布订单创建事件
            await self.event_manager.publish(TradingEventType.ORDER_CREATED, {
                "order_id": order_id,
                "user_id": user_id,
                "symbol": order_request.symbol,
                "volume": str(order_request.volume),
                "price": str(order_request.price or 0)
            })
            
            # 7. 提交到交易网关
            await self._submit_order_to_gateway(order)
            
            # 8. 记录审计日志
            await self._create_audit_log(
                session, user_id, "order_create", "order", order_id,
                success=True, details=order_request.dict()
            )
            
            await session.commit()
            
            self._order_count += 1
            self.logger.info(f"订单创建成功: {order_id}")
            
            return {
                "order_id": order_id,
                "id": order.id
            }
            
        except Exception as e:
            await session.rollback()
            self._error_count += 1
            self.logger.error(f"订单创建失败: {e}", exc_info=True)
            
            # 记录失败审计日志 (在一个新的会话中或在回滚后)
            # 注意: 在这里创建审计日志可能需要特殊的会话处理
            raise TradingServiceError(f"订单创建失败: {e}")
    
    async def cancel_order(self, session: AsyncSession, user_id: str, order_id: str, reason: Optional[str] = None) -> bool:
        """
        撤销交易订单
        
        Args:
            session: 数据库会话
            user_id: 用户ID
            order_id: 订单编号
            reason: 撤销原因
            
        Returns:
            撤销是否成功
            
        Raises:
            OrderNotFoundError: 订单不存在
            TradingServiceError: 订单状态不允许撤销
        """
        try:
            # 1. 查询订单
            order = await self._get_order_by_id(session, order_id)
            if not order:
                raise OrderNotFoundError(f"订单不存在: {order_id}")
            
            # 2. 检查用户权限
            if order.user_id != user_id:
                raise TradingServiceError("无权限操作此订单")
            
            # 3. 检查订单状态
            if not order.is_active():
                raise TradingServiceError(f"订单状态不允许撤销: {order.status}")
            
            # 4. 更新订单状态
            order.status = OrderStatus.CANCELLED
            order.cancelled_at = datetime.utcnow()
            order.updated_at = datetime.utcnow()
            
            # 5. 通知网关撤销订单
            await self._cancel_order_in_gateway(order)
            
            # 6. 发布订单撤销事件
            await self.event_manager.publish(TradingEventType.ORDER_CANCELLED, {
                "order_id": order_id,
                "user_id": user_id,
                "reason": reason or "用户撤销"
            })
            
            # 7. 记录审计日志
            await self._create_audit_log(
                session, user_id, "order_cancel", "order", order_id,
                success=True, details={"reason": reason}
            )
            
            await session.commit()
            
            self.logger.info(f"订单撤销成功: {order_id}")
            return True
            
        except Exception as e:
            await session.rollback()
            self._error_count += 1
            self.logger.error(f"订单撤销失败: {e}", exc_info=True)
            raise TradingServiceError(f"订单撤销失败: {e}")
    
    async def get_orders(self, session: AsyncSession, user_id: str, query_params: OrderQueryParams) -> Tuple[List[Order], int]:
        """
        查询用户订单列表
        
        Args:
            session: 数据库会话
            user_id: 用户ID
            query_params: 查询参数
            
        Returns:
            订单列表和总数量
        """
        # 构建查询条件
        conditions = [Order.user_id == user_id]
        
        if query_params.symbol:
            conditions.append(Order.symbol == query_params.symbol)
        if query_params.exchange:
            conditions.append(Order.exchange == query_params.exchange)
        if query_params.status:
            conditions.append(Order.status == query_params.status)
        if query_params.direction:
            conditions.append(Order.direction == query_params.direction)
        if query_params.strategy_id:
            conditions.append(Order.strategy_id == query_params.strategy_id)
        if query_params.start_time:
            conditions.append(Order.created_at >= query_params.start_time)
        if query_params.end_time:
            conditions.append(Order.created_at <= query_params.end_time)
        
        # 查询总数
        count_query = select(func.count(Order.id)).where(and_(*conditions))
        total_count = await session.scalar(count_query)
        
        # 查询数据
        query = (
            select(Order)
            .where(and_(*conditions))
            .options(selectinload(Order.trades))
            .order_by(desc(Order.created_at))
            .offset((query_params.page - 1) * query_params.size)
            .limit(query_params.size)
        )
        
        result = await session.execute(query)
        orders = result.scalars().all()
        
        return orders, total_count
    
    async def get_order_detail(self, session: AsyncSession, user_id: str, order_id: str) -> Optional[Order]:
        """
        获取订单详情
        
        Args:
            session: 数据库会话
            user_id: 用户ID
            order_id: 订单编号
            
        Returns:
            订单详情
        """
        query = (
            select(Order)
            .where(and_(
                Order.order_id == order_id,
                Order.user_id == user_id
            ))
            .options(selectinload(Order.trades))
        )
        
        result = await session.execute(query)
        return result.scalar_one_or_none()
    
    # ==================== 成交管理 ====================
    
    async def process_trade(self, session: AsyncSession, trade_data: Dict[str, Any]) -> bool:
        """
        处理交易成交
        
        Args:
            session: 数据库会话
            trade_data: 成交数据
            
        Returns:
            处理是否成功
        """
        try:
            # 1. 查找对应订单
            order = await self._get_order_by_id(session, trade_data["order_id"])
            if not order:
                self.logger.warning(f"订单不存在，忽略成交: {trade_data['order_id']}")
                return False
            
            # 2. 创建成交记录
            trade = Trade(
                id=str(uuid.uuid4()),
                trade_id=trade_data["trade_id"],
                order_id=order.order_id,
                user_id=order.user_id,
                symbol=trade_data["symbol"],
                exchange=trade_data["exchange"],
                gateway=trade_data.get("gateway"),
                direction=TradeDirection.BUY if trade_data["direction"] == "LONG" else TradeDirection.SELL,
                offset=trade_data.get("offset"),
                volume=Decimal(str(trade_data["volume"])),
                price=Decimal(str(trade_data["price"])),
                turnover=Decimal(str(trade_data["turnover"])),
                commission=Decimal(str(trade_data.get("commission", 0))),
                trade_time=trade_data.get("trade_time", datetime.utcnow()),
                external_trade_id=trade_data.get("external_trade_id")
            )
            
            session.add(trade)
            
            # 3. 更新订单状态
            await self._update_order_on_trade(session, order, trade)
            
            # 4. 更新持仓
            await self._update_position_on_trade(session, order.user_id, trade)
            
            # 5. 更新资金账户
            await self._update_account_on_trade(session, order.user_id, trade)
            
            # 6. 发布成交事件
            await self.event_manager.publish(TradingEventType.TRADE_FILLED, {
                "trade_id": trade.trade_id,
                "order_id": order.order_id,
                "user_id": order.user_id,
                "symbol": trade.symbol,
                "volume": str(trade.volume),
                "price": str(trade.price)
            })
            
            await session.commit()
            
            self._trade_count += 1
            self.logger.info(f"成交处理完成: {trade.trade_id}")
            
            return True
            
        except Exception as e:
            await session.rollback()
            self._error_count += 1
            self.logger.error(f"成交处理失败: {e}", exc_info=True)
            raise TradingServiceError(f"成交处理失败: {e}")
    
    async def get_trades(self, session: AsyncSession, user_id: str, query_params: TradeQueryParams) -> Tuple[List[Trade], int]:
        """
        查询用户成交列表
        
        Args:
            session: 数据库会话
            user_id: 用户ID
            query_params: 查询参数
            
        Returns:
            成交列表和总数量
        """
        # 构建查询条件
        conditions = [Trade.user_id == user_id]
        
        if query_params.symbol:
            conditions.append(Trade.symbol == query_params.symbol)
        if query_params.exchange:
            conditions.append(Trade.exchange == query_params.exchange)
        if query_params.direction:
            conditions.append(Trade.direction == query_params.direction)
        if query_params.order_id:
            conditions.append(Trade.order_id == query_params.order_id)
        if query_params.start_time:
            conditions.append(Trade.trade_time >= query_params.start_time)
        if query_params.end_time:
            conditions.append(Trade.trade_time <= query_params.end_time)
        
        # 查询总数
        count_query = select(func.count(Trade.id)).where(and_(*conditions))
        total_count = await session.scalar(count_query)
        
        # 查询数据
        query = (
            select(Trade)
            .where(and_(*conditions))
            .order_by(desc(Trade.trade_time))
            .offset((query_params.page - 1) * query_params.size)
            .limit(query_params.size)
        )
        
        result = await session.execute(query)
        trades = result.scalars().all()
        
        return trades, total_count
    
    # ==================== 持仓管理 ====================
    
    async def get_positions(self, session: AsyncSession, user_id: str, query_params: PositionQueryParams) -> Tuple[List[Position], int]:
        """
        查询用户持仓列表
        
        Args:
            session: 数据库会话
            user_id: 用户ID
            query_params: 查询参数
            
        Returns:
            持仓列表和总数量
        """
        # 构建查询条件
        conditions = [
            Position.user_id == user_id,
            Position.volume > 0  # 只返回有持仓的记录
        ]
        
        if query_params.symbol:
            conditions.append(Position.symbol == query_params.symbol)
        if query_params.exchange:
            conditions.append(Position.exchange == query_params.exchange)
        if query_params.direction:
            conditions.append(Position.direction == query_params.direction)
        if query_params.strategy_id:
            conditions.append(Position.strategy_id == query_params.strategy_id)
        
        # 查询总数
        count_query = select(func.count(Position.id)).where(and_(*conditions))
        total_count = await session.scalar(count_query)
        
        # 查询数据
        query = (
            select(Position)
            .where(and_(*conditions))
            .order_by(desc(Position.updated_at))
            .offset((query_params.page - 1) * query_params.size)
            .limit(query_params.size)
        )
        
        result = await session.execute(query)
        positions = result.scalars().all()
        
        return positions, total_count
    
    # ==================== 资金管理 ====================
    
    async def get_accounts(self, session: AsyncSession, user_id: str) -> List[Account]:
        """
        获取用户资金账户列表
        
        Args:
            session: 数据库会话
            user_id: 用户ID
            
        Returns:
            资金账户列表
        """
        query = (
            select(Account)
            .where(Account.user_id == user_id)
            .order_by(Account.gateway, Account.currency)
        )
        
        result = await session.execute(query)
        return result.scalars().all()
    
    # ==================== 网关管理 ====================
    
    async def create_gateway(self, session: AsyncSession, gateway_request: GatewayRequest) -> str:
        """
        创建交易网关
        
        Args:
            session: 数据库会话
            gateway_request: 网关请求
            
        Returns:
            网关ID
        """
        try:
            # 检查网关名称是否已存在
            existing = await session.scalar(
                select(Gateway).where(Gateway.gateway_name == gateway_request.gateway_name)
            )
            if existing:
                raise TradingServiceError(f"网关名称已存在: {gateway_request.gateway_name}")
            
            # 创建网关记录
            gateway = Gateway(
                id=str(uuid.uuid4()),
                gateway_name=gateway_request.gateway_name,
                gateway_type=gateway_request.gateway_type,
                description=gateway_request.description,
                host=gateway_request.host,
                port=gateway_request.port,
                username=gateway_request.username,
                password=gateway_request.password,
                config_json=json.dumps(gateway_request.config_json) if gateway_request.config_json else None,
                status=GatewayStatus.DISCONNECTED,
                is_active=True
            )
            
            session.add(gateway)
            await session.commit()
            
            self.logger.info(f"网关创建成功: {gateway_request.gateway_name}")
            return gateway.id
            
        except Exception as e:
            await session.rollback()
            self.logger.error(f"网关创建失败: {e}", exc_info=True)
            raise TradingServiceError(f"网关创建失败: {e}")
    
    async def connect_gateway(self, session: AsyncSession, gateway_name: str, force_reconnect: bool = False) -> bool:
        """
        连接交易网关
        
        Args:
            session: 数据库会话
            gateway_name: 网关名称
            force_reconnect: 是否强制重连
            
        Returns:
            连接是否成功
        """
        try:
            # 查找网关
            gateway = await session.scalar(
                select(Gateway).where(Gateway.gateway_name == gateway_name)
            )
            if not gateway:
                raise TradingServiceError(f"网关不存在: {gateway_name}")
            
            if not gateway.is_active:
                raise TradingServiceError(f"网关已禁用: {gateway_name}")
            
            # 检查当前连接状态
            if gateway.status == GatewayStatus.CONNECTED and not force_reconnect:
                return True
            
            # 更新连接状态
            gateway.status = GatewayStatus.CONNECTING
            gateway.last_connect_time = datetime.utcnow()
            gateway.connect_count += 1
            
            # 实际连接网关（这里应该调用具体的网关连接逻辑）
            success = await self._connect_gateway_impl(gateway)
            
            # 更新最终状态
            gateway.status = GatewayStatus.CONNECTED if success else GatewayStatus.ERROR
            if not success:
                gateway.error_message = "连接失败"
                gateway.last_disconnect_time = datetime.utcnow()
            else:
                gateway.error_message = None
            
            await session.commit()
            
            if success:
                self._gateway_connections[gateway_name] = gateway
                self.logger.info(f"网关连接成功: {gateway_name}")
            else:
                self.logger.error(f"网关连接失败: {gateway_name}")
            
            return success
            
        except Exception as e:
            await session.rollback()
            self.logger.error(f"网关连接异常: {e}", exc_info=True)
            raise TradingServiceError(f"网关连接异常: {e}")
    
    # ==================== 统计分析 ====================
    
    async def get_trading_statistics(self, session: AsyncSession, user_id: str) -> TradingStatistics:
        """
        获取交易统计数据
        
        Args:
            session: 数据库会话
            user_id: 用户ID
            
        Returns:
            交易统计数据
        """
        # 订单统计
        order_stats = await session.execute(
            select(
                func.count(Order.id).label('total_orders'),
                func.sum(func.case((Order.status.in_([OrderStatus.SUBMITTING, OrderStatus.SUBMITTED, OrderStatus.PARTIAL_FILLED]), 1), else_=0)).label('active_orders'),
                func.sum(func.case((Order.status == OrderStatus.FILLED, 1), else_=0)).label('filled_orders'),
                func.sum(func.case((Order.status == OrderStatus.CANCELLED, 1), else_=0)).label('cancelled_orders')
            ).where(Order.user_id == user_id)
        )
        order_result = order_stats.first()
        
        # 成交统计
        trade_stats = await session.execute(
            select(
                func.count(Trade.id).label('total_trades'),
                func.sum(Trade.volume).label('total_volume'),
                func.sum(Trade.turnover).label('total_turnover'),
                func.sum(Trade.commission).label('total_commission')
            ).where(Trade.user_id == user_id)
        )
        trade_result = trade_stats.first()
        
        # 持仓统计
        position_stats = await session.execute(
            select(
                func.count(Position.id).label('active_positions'),
                func.sum(Position.volume * Position.price).label('total_position_value')
            ).where(and_(
                Position.user_id == user_id,
                Position.volume > 0
            ))
        )
        position_result = position_stats.first()
        
        # 资金统计
        account_stats = await session.execute(
            select(
                func.sum(Account.total_pnl).label('total_pnl'),
                func.sum(Account.daily_pnl).label('daily_pnl')
            ).where(Account.user_id == user_id)
        )
        account_result = account_stats.first()
        
        # 网关和策略统计
        gateway_count = len([g for g in self._gateway_connections.values() if g.status == GatewayStatus.CONNECTED])
        strategy_count = await session.scalar(
            select(func.count(Strategy.id)).where(and_(
                Strategy.user_id == user_id,
                Strategy.is_active == True
            ))
        )
        
        return TradingStatistics(
            total_orders=order_result.total_orders or 0,
            active_orders=order_result.active_orders or 0,
            filled_orders=order_result.filled_orders or 0,
            cancelled_orders=order_result.cancelled_orders or 0,
            
            total_trades=trade_result.total_trades or 0,
            total_volume=trade_result.total_volume or Decimal('0'),
            total_turnover=trade_result.total_turnover or Decimal('0'),
            total_commission=trade_result.total_commission or Decimal('0'),
            
            total_pnl=account_result.total_pnl or Decimal('0'),
            daily_pnl=account_result.daily_pnl or Decimal('0'),
            
            active_positions=position_result.active_positions or 0,
            total_position_value=position_result.total_position_value or Decimal('0'),
            
            connected_gateways=gateway_count,
            active_strategies=strategy_count or 0
        )
    
    # ==================== 私有辅助方法 ====================
    
    async def _perform_risk_check(self, session: AsyncSession, user_id: str, order_request: OrderRequest):
        """执行风控检查"""
        risk_result = await self.risk_manager.check_order_risk(user_id, order_request.dict())
        if not risk_result.passed:
            # 记录风控日志
            risk_record = Risk(
                id=str(uuid.uuid4()),
                user_id=user_id,
                risk_type=risk_result.risk_type,
                risk_level=risk_result.risk_level,
                risk_message=risk_result.message,
                action_taken="blocked",
                is_blocked=True,
                symbol=order_request.symbol,
                volume=order_request.volume,
                price=order_request.price
            )
            session.add(risk_record)
            await session.commit()
            
            raise RiskCheckFailedError(risk_result.message)
    
    async def _get_contract(self, session: AsyncSession, symbol: str, exchange: str) -> Optional[Contract]:
        """获取合约信息"""
        cache_key = f"{symbol}.{exchange}"
        if cache_key in self._contract_cache:
            return self._contract_cache[cache_key]
        
        contract = await session.scalar(
            select(Contract).where(and_(
                Contract.symbol == symbol,
                Contract.exchange == exchange
            ))
        )
        
        if contract:
            self._contract_cache[cache_key] = contract
        
        return contract
    
    async def _check_funds_sufficiency(self, session: AsyncSession, user_id: str, order_request: OrderRequest):
        """检查资金充足性"""
        # 这里应该实现具体的资金检查逻辑
        # 暂时简化处理
        pass
    
    async def _get_order_by_id(self, session: AsyncSession, order_id: str) -> Optional[Order]:
        """根据订单ID获取订单"""
        return await session.scalar(
            select(Order).where(Order.order_id == order_id)
        )
    
    async def _submit_order_to_gateway(self, order: Order):
        """提交订单到交易网关"""
        # 这里应该实现具体的网关提交逻辑
        # 暂时模拟处理
        order.status = OrderStatus.SUBMITTED
        order.submitted_at = datetime.utcnow()
    
    async def _cancel_order_in_gateway(self, order: Order):
        """在网关中撤销订单"""
        # 这里应该实现具体的网关撤销逻辑
        pass
    
    async def _update_order_on_trade(self, session: AsyncSession, order: Order, trade: Trade):
        """根据成交更新订单状态"""
        order.traded_volume += trade.volume
        order.remaining_volume = order.volume - order.traded_volume
        
        # 计算成交均价
        if order.traded_volume > 0:
            total_turnover = order.average_price * (order.traded_volume - trade.volume) + trade.price * trade.volume
            order.average_price = total_turnover / order.traded_volume
        
        # 更新订单状态
        if order.remaining_volume <= 0:
            order.status = OrderStatus.FILLED
        else:
            order.status = OrderStatus.PARTIAL_FILLED
        
        order.updated_at = datetime.utcnow()
    
    async def _update_position_on_trade(self, session: AsyncSession, user_id: str, trade: Trade):
        """根据成交更新持仓"""
        # 使用持仓计算器更新持仓
        await self.position_calculator.update_position(session, user_id, trade)
    
    async def _update_account_on_trade(self, session: AsyncSession, user_id: str, trade: Trade):
        """根据成交更新资金账户"""
        # 查找对应的资金账户
        account = await session.scalar(
            select(Account).where(and_(
                Account.user_id == user_id,
                Account.gateway == trade.gateway
            ))
        )
        
        if account:
            # 更新资金
            if trade.direction == TradeDirection.BUY:
                account.frozen -= trade.turnover + trade.commission
                account.available = account.balance - account.frozen
            else:
                account.available += trade.turnover - trade.commission
                account.balance = account.available + account.frozen
            
            account.commission += trade.commission
            account.updated_at = datetime.utcnow()
    
    async def _connect_gateway_impl(self, gateway: Gateway) -> bool:
        """实际连接网关的实现"""
        # 这里应该实现具体的网关连接逻辑
        # 暂时返回成功
        return True
    
    async def _create_audit_log(self, session: AsyncSession, user_id: str, action: str, 
                              resource_type: str, resource_id: Optional[str],
                              success: bool, error_message: Optional[str] = None,
                              details: Optional[Dict[str, Any]] = None):
        """创建审计日志"""
        audit = Audit(
            id=str(uuid.uuid4()),
            user_id=user_id,
            action=action,
            resource_type=resource_type,
            resource_id=resource_id,
            ip_address="0.0.0.0",  # 默认地址，应该从请求上下文获取
            success=success,
            error_message=error_message,
            details_json=json.dumps(details, default=str) if details else None
        )
        session.add(audit)
        # 注意: 这里的commit可能会干扰上层函数的事务管理
        # 在新的模式下，应该由上层函数统一commit
        # await session.commit()
